package com.dx.financehy.modules.security.utils;

import com.dx.financehy.exception.BadRequestException;
import com.dx.financehy.modules.security.config.bean.LoginProperties;
import com.dx.financehy.utils.CacheKey;
import com.dx.financehy.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * @描述：
 * @作者：CLD
 * @创建时间：2022-04-14 16:52
 * </pre>
 **/
@RequiredArgsConstructor
@Slf4j
@Component
public class LoginUtil {

    private final RedisUtils redisUtils;
    private final LoginProperties loginProperties;

    /**
     * 登录错误次数计数
     *
     * @param userName
     */
    public void incrementCount(String userName) {
        long failTimeInterval = loginProperties.getLoginFail().getFailTimeInterval();
        long failLockTime = loginProperties.getLoginFail().getFailLockTime();
        int failRetryTimes = loginProperties.getLoginFail().getFailRetryTimes();
        int failCountTips = loginProperties.getLoginFail().getFailCountTips();

        String loginFailedCountKey = loginFailedCountKey(userName);
        redisUtils.increment(loginFailedCountKey, 1L);
        redisUtils.expire(loginFailedCountKey, failTimeInterval, TimeUnit.MINUTES);

        Object o = redisUtils.get(loginFailedCountKey);
        int count = Integer.parseInt(o.toString());
        if (count == failCountTips) { // 第三次错误提醒
            throw new BadRequestException(String.format("%d分钟内连续登录失败%d次，账号将被锁定%d分钟", failTimeInterval, failRetryTimes, failLockTime));
        } else if (count == failRetryTimes) { // 第五次锁定账号
            //设置15分钟的过期时间
            redisUtils.set(loginFailedLockKey(userName), userName + ":locked", failLockTime, TimeUnit.MINUTES);
            redisUtils.del(loginFailedCountKey(userName));

            throw new BadRequestException(String.format("账号被锁定，%d分钟后再试", failLockTime));
        }
    }

    public String loginFailedCountKey(String userName) {
        return CacheKey.LOGIN_FAIL_COUNT + userName;
    }

    public String loginFailedLockKey(String userName) {
        return CacheKey.LOGIN_FAIL_LOCK + userName;
    }

}
